package com.zhangyj.util;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import com.zhangyj.entitis.TreeItem;

public class AccordionCreator {

	private String contextPath;
	private List<TreeItem> milist;

	public AccordionCreator(List<TreeItem> list, String contextPath) {
		this.contextPath = null;
		milist = list;
		this.contextPath = contextPath;
		init();
	}

	private void init() {
		if (contextPath == null) {
			contextPath = "";
		}
	}

	public String getHtml() throws SQLException {
		StringBuilder buffer = new StringBuilder();
		buildHtmlFromList(buffer);
		return buffer.toString();
	}

	private void buildHtmlFromList(StringBuilder buffer) {
		String parentCode = null;
		boolean isFirst = false;
		for (Iterator<TreeItem> itr = milist.iterator(); itr.hasNext();) {
			TreeItem item = itr.next();
			int id = item.getId();
			String code = item.getCode();
			String desc = item.getDescription();
			boolean isleaf = item.isLeaf();
			if (parentCode == null) {
				parentCode = code;
				appendTitle(buffer, id, code, desc);
				isFirst = true;
			} else if (code.startsWith(parentCode)) {
				appendItem(buffer, id, code, desc, isleaf,isFirst);
				isFirst = false;
			} else {
				parentCode = code;
				appendTail(buffer);
				appendTitle(buffer, id, code, desc);
				isFirst = true;
			}
		}

		if (parentCode != null) {
			appendTail(buffer);
		}
	}

	private void appendTitle(StringBuilder buffer, int id, String code, String desc) {
		//buffer.append("<h2><a href=\"#\">" + desc + "</a></h2><div class='category'>");
		buffer.append("<div title=\"").append(desc).append("\" iconCls=\"icon-ok\" class='category' >");
	}

	private void appendItem(StringBuilder buffer, int id, String code, String desc, boolean isleaf,boolean isFirst) {
		if (isleaf) {
			if (isFirst == false) {
				buffer.append("<span class='operetor'>|</span>");	
			}
			
			buffer.append("<a href='javascript:void(0)' onclick='uf_fireEvent(this)'  title=\"").append(desc).append("\"  uid=\"").append(id).append("\" ").append("ucode=\"").append(code).append("\">");
			buffer.append(desc);
			buffer.append("</a>");
			
		} else {
			buffer.append("<br/><span class='category'>");
			buffer.append(desc);
			buffer.append("</span><br/>");
		}

	}

	private void appendTail(StringBuilder buffer) {
		buffer.append("</div>");
	}

}
